using System;
using System.Collections.Generic;
using System.IO;

namespace Dojo {
    public class FileSearcher {
        private string dojoHome;
        private string sourceRoot;

        public FileSearcher(string dojoHome, string sourceRoot) {
            this.dojoHome = dojoHome ;
            this.sourceRoot = sourceRoot + Path.DirectorySeparatorChar;
        }

        public virtual IList<ResolvedFile> Search() {
            List<ResolvedFile> files = new List<ResolvedFile>();
            DirectoryInfo sourceDir = new DirectoryInfo(sourceRoot);
            files.AddRange(search(sourceDir.FullName));
            return files;
        }

        private static bool validFiletype(FileInfo file) {
            return file.Extension.Equals(".html",StringComparison.OrdinalIgnoreCase) || 
                   file.Extension.Equals(".htm",StringComparison.OrdinalIgnoreCase) ||
                   file.Extension.Equals(".js",StringComparison.OrdinalIgnoreCase);
        }

        private IList<ResolvedFile> search(string directoryName) {
            List<ResolvedFile> files = new List<ResolvedFile>();
            DirectoryInfo sourceDir = new DirectoryInfo(directoryName);
            foreach (FileInfo file in sourceDir.GetFiles())
            {
                if (validFiletype(file))
                {
                    files.Add(new ResolvedFile(file.Name, file.DirectoryName));
                }
            }
            
            foreach (DirectoryInfo directory in sourceDir.GetDirectories()) {
                if(validDirectory(directory)) {
                    files.AddRange(search(directory.FullName));
                }
            }
            return files;
        }

        private bool validDirectory(DirectoryInfo directory) {
            return !(/*directory.FullName.Equals(this.dojoHome,StringComparison.OrdinalIgnoreCase) ||*/ 
                     directory.Name.Equals(".svn",StringComparison.OrdinalIgnoreCase));
        }
    }
}